package com.okex.demo.controller;

import com.okex.demo.model.Account;
import com.okex.demo.service.AccountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Controller
@RequestMapping("/accounts")
public class AccountController {

    private static final Logger log = LoggerFactory.getLogger(AccountController.class);

    @Autowired
    private AccountService accountService;
    
    /**
     * 账户列表页面
     */
    @GetMapping("")
    public String showAccountListView(Model model) {
        List<Account> accounts = accountService.findAll();
        model.addAttribute("accounts", accounts);
        return "accounts";
    }
    
    /**
     * 账户详情页面 - 重定向到编辑页面
     */
    @GetMapping("/{id}")
    public String showAccountDetailView(@PathVariable Long id) {
        return "redirect:/accounts/edit?id=" + id;
    }
    
    /**
     * 创建/编辑账户页面
     */
    @GetMapping("/edit")
    public String showAccountEditView(
            @RequestParam(required = false) Long id, 
            @RequestParam(required = false) String prefilledInstId,
            Model model) {
        
        Account accountEntity = new Account();
        // 初始化默认值
        initializeDefaultValues(accountEntity);
        
        if (id != null) {
            // 编辑现有产品
            accountService.findById(id).ifPresent(account -> {
                // 复制所有字段
                copyAllFields(accountEntity, account);
                log.info("编辑产品: ID={}, 名称={}", account.getId(), account.getAccountName());
            });
        } else if (prefilledInstId != null && !prefilledInstId.isEmpty()) {
            // 创建新产品，预填产品ID
            log.info("使用预填产品ID创建新产品: {}", prefilledInstId);
            accountEntity.setInstId(prefilledInstId);
            
            // 尝试生成一个合理的产品名称
            String baseCoin = prefilledInstId.split("-")[0];
            String suggestedName = baseCoin + "永续合约";
            accountEntity.setAccountName(suggestedName);
            
            // 添加提示消息
            model.addAttribute("infoMessage", "您正在创建新产品 " + prefilledInstId + "，请完善产品信息后保存。");
        }
        
        model.addAttribute("account", accountEntity);
        return "account-form";
    }
    
    /**
     * 初始化新账户的默认值
     */
    private void initializeDefaultValues(Account accountEntity) {
        accountEntity.setCrossPriceDiff(new java.math.BigDecimal("100"));     // 全仓价差
        accountEntity.setCrossTakeProfit(new java.math.BigDecimal("1000"));   // 全仓止盈
        accountEntity.setCrossMargin(new java.math.BigDecimal("50"));         // 全仓保证金
        accountEntity.setCrossPriceDiffMargin(new java.math.BigDecimal("50")); // 全仓价差保证金
        accountEntity.setCrossLongReplenishCount(1);                          // 全仓多仓补仓次数
        accountEntity.setCrossShortReplenishCount(1);                         // 全仓空仓补仓次数
        accountEntity.setCrossLongCost(java.math.BigDecimal.ZERO);            // 全仓多仓成本
        accountEntity.setCrossShortCost(java.math.BigDecimal.ZERO);           // 全仓空仓成本
        accountEntity.setFaceValue(new java.math.BigDecimal("0.001"));        // 面值
        accountEntity.setConversionPriceDiff(new java.math.BigDecimal("100")); // 转换价差
        accountEntity.setCrossToIsolatedShortPriceDiff(java.math.BigDecimal.ZERO); // 全仓转逐仓空仓价差
        accountEntity.setCrossToIsolatedLongCost(java.math.BigDecimal.ZERO);  // 全仓转逐仓多仓成本
        accountEntity.setIsolatedPriceDiff(new java.math.BigDecimal("100"));  // 逐仓价差
        accountEntity.setIsolatedMargin(new java.math.BigDecimal("50"));      // 逐仓保证金
        accountEntity.setIsolatedPriceDiffMargin(new java.math.BigDecimal("50")); // 逐仓价差保证金
        accountEntity.setIsolatedLongReplenishCount(1);                       // 逐仓多仓补仓次数
        accountEntity.setIsolatedShortReplenishCount(1);                      // 逐仓空仓补仓次数
        accountEntity.setLeverage("20");                                      // 杠杆倍数
        accountEntity.setIsTransferIsolatedShort(true);                       // 是否转移逐仓空仓
        accountEntity.setIsTransferIsolatedLong(true);                        // 是否转移逐仓多仓
        accountEntity.setIsolatedLongCost(java.math.BigDecimal.ZERO);         // 逐仓多仓成本
        accountEntity.setIsolatedShortCost(java.math.BigDecimal.ZERO);        // 逐仓空仓成本
    }
    
    /**
     * 从源账户复制所有字段到目标账户
     */
    private void copyAllFields(Account target, Account source) {
        target.setId(source.getId());
        target.setInstId(source.getInstId());
        target.setAccountName(source.getAccountName());
        target.setCrossPriceDiff(source.getCrossPriceDiff());
        target.setCrossTakeProfit(source.getCrossTakeProfit());
        target.setCrossMargin(source.getCrossMargin());
        target.setCrossPriceDiffMargin(source.getCrossPriceDiffMargin());
        target.setCrossLongReplenishCount(source.getCrossLongReplenishCount());
        target.setCrossShortReplenishCount(source.getCrossShortReplenishCount());
        target.setCrossLongCost(source.getCrossLongCost());
        target.setCrossShortCost(source.getCrossShortCost());
        target.setFaceValue(source.getFaceValue());
        target.setConversionPriceDiff(source.getConversionPriceDiff());
        target.setCrossToIsolatedShortPriceDiff(source.getCrossToIsolatedShortPriceDiff());
        target.setCrossToIsolatedLongCost(source.getCrossToIsolatedLongCost());
        target.setIsolatedPriceDiff(source.getIsolatedPriceDiff());
        target.setIsolatedMargin(source.getIsolatedMargin());
        target.setIsolatedPriceDiffMargin(source.getIsolatedPriceDiffMargin());
        target.setIsolatedLongReplenishCount(source.getIsolatedLongReplenishCount());
        target.setIsolatedShortReplenishCount(source.getIsolatedShortReplenishCount());
        target.setLeverage(source.getLeverage());
        target.setIsTransferIsolatedShort(source.getIsTransferIsolatedShort());
        target.setIsTransferIsolatedLong(source.getIsTransferIsolatedLong());
        target.setIsolatedLongCost(source.getIsolatedLongCost());
        target.setIsolatedShortCost(source.getIsolatedShortCost());
        target.setCreatedAt(source.getCreatedAt());
        target.setUpdatedAt(source.getUpdatedAt());
    }
    
    /**
     * 保存账户
     */
    @PostMapping("/save")
    public String saveAccount(Account accountEntity, Model model, RedirectAttributes redirectAttributes) {
        try {
            // 基本验证 - 只验证产品ID
            if (accountEntity.getInstId() == null || accountEntity.getInstId().trim().isEmpty()) {
                redirectAttributes.addFlashAttribute("errorMessage", "产品ID不能为空");
                if (accountEntity.getId() != null) {
                    return "redirect:/accounts/edit?id=" + accountEntity.getId();
                } else {
                    return "redirect:/accounts/edit";
                }
            }
            
            // 检查是否已存在相同instId的账户（对于新建产品）
            if (accountEntity.getId() == null) {
                Optional<Account> existingAccount = accountService.findByInstId(accountEntity.getInstId());
                if (existingAccount.isPresent()) {
                    redirectAttributes.addFlashAttribute("errorMessage", "产品ID " + accountEntity.getInstId() + " 已存在，请使用其他产品ID");
                    return "redirect:/accounts/edit";
                }
            } else {
                // 对于更新，检查是否与其他产品的instId冲突
                Optional<Account> existingWithSameInstId = accountService.findByInstId(accountEntity.getInstId());
                if (existingWithSameInstId.isPresent() && !existingWithSameInstId.get().getId().equals(accountEntity.getId())) {
                    redirectAttributes.addFlashAttribute("errorMessage", "产品ID " + accountEntity.getInstId() + " 已被其他产品使用，请使用其他产品ID");
                    return "redirect:/accounts/edit?id=" + accountEntity.getId();
                }
                
                // 由于表单不提交创建时间，强制从数据库获取
                Optional<Account> existingAccountOpt = accountService.findById(accountEntity.getId());
                if (existingAccountOpt.isPresent()) {
                    Account existingAccount = existingAccountOpt.get();
                    log.info("从数据库获取原始产品信息: ID={}, 创建时间={}", existingAccount.getId(), existingAccount.getCreatedAt());
                    
                    // 强制设置创建时间为从数据库获取的值
                    accountEntity.setCreatedAt(existingAccount.getCreatedAt());
                    
                    log.info("更新产品: {}, ID: {}", accountEntity.getAccountName(), accountEntity.getId());
                }
            }
            
            // 使用新的保留字段的保存方法
            accountService.saveWithFieldPreservation(accountEntity);
            
            // 添加成功消息
            redirectAttributes.addFlashAttribute("successMessage", 
                accountEntity.getId() == null ? "产品添加成功！" : "产品更新成功！");
                
            return "redirect:/accounts";
            
        } catch (Exception e) {
            log.error("保存产品失败:", e);
            // 添加详细的错误消息
            String errorMsg = "操作失败";
            
            // 对已知错误类型进行特殊处理
            if (e.getMessage() != null) {
                if (e.getMessage().contains("constraint") && e.getMessage().contains("unique")) {
                    errorMsg = "产品ID已存在，请使用其他产品ID";
                } else {
                    errorMsg = "操作失败：" + e.getMessage();
                }
            }
            
            redirectAttributes.addFlashAttribute("errorMessage", errorMsg);
            
            // 根据是否有ID确定重定向目标
            if (accountEntity.getId() != null) {
                return "redirect:/accounts/edit?id=" + accountEntity.getId();
            } else {
                return "redirect:/accounts/edit";
            }
        }
    }
    
    /**
     * 删除账户
     */
    @PostMapping("/delete/{id}")
    public String deleteAccount(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        try {
            // 获取账户名称用于消息提示
            String accountName = accountService.findById(id)
                    .map(a -> a.getAccountName())
                    .orElse("未知产品");
            
            accountService.delete(id);
            // 添加成功消息
            redirectAttributes.addFlashAttribute("successMessage", "产品 '" + accountName + "' 已成功删除！");
        } catch (Exception e) {
            // 添加错误消息
            redirectAttributes.addFlashAttribute("errorMessage", "删除失败：" + e.getMessage());
        }
        return "redirect:/accounts";
    }
    
    /**
     * 获取所有账户API
     */
    @GetMapping("/api/list")
    @ResponseBody
    public List<Account> getAllAccounts() {
        return accountService.findAll();
    }
    
    /**
     * 获取账户详情API
     */
    @GetMapping("/api/{id}")
    @ResponseBody
    public ResponseEntity<Account> getAccount(@PathVariable Long id) {
        return accountService.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
    
    /**
     * 保存账户API
     */
    @PostMapping("/api/save")
    @ResponseBody
    public Account createOrUpdateAccount(@RequestBody Account accountEntity) {
        return accountService.saveWithFieldPreservation(accountEntity);
    }
    
    /**
     * 删除账户API
     */
    @DeleteMapping("/api/{id}")
    @ResponseBody
    public ResponseEntity<Void> deleteAccountApi(@PathVariable Long id) {
        accountService.delete(id);
        return ResponseEntity.ok().build();
    }
    
    /**
     * 通过产品ID查找账户API
     */
    @GetMapping("/api/find-by-instid")
    @ResponseBody
    public ResponseEntity<Account> getAccountByInstId(@RequestParam String instId) {
        log.info("正在查找产品ID: {}", instId);
        
        Optional<Account> accountOpt = accountService.findByInstIdWithFlexibleMatching(instId);
        
        if (accountOpt.isPresent()) {
            return ResponseEntity.ok(accountOpt.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }
} 
